package com.education.platform.common.qiniu;

import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.StringUtils;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 七牛云服务
 * @author tomato
 */
@Service
public class QiNiuServiceImpl implements QiNiuService {

    @Autowired
    private QiNiuConfig config;

    /**
     * 获取上传凭证
     * @param
     * @return
     */
    @Override
    public String getUploadToken() {
        this.checkConfig();
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        String upToken = auth.uploadToken(config.getBucket());
        System.out.println(upToken);
        return upToken;
    }


    /**
     * 私有bucket ，下载，需要下载凭证
     * 共有bucket，   直接访问url访问
     * @param url
     * @return
     */
    @Override
    public String getPrivateDownLoadUrl(String url) {
        this.checkConfig();
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        // 1小时，可以自定义链接过期时间
        long expireInSeconds = 3600;
        String downloadUrl = auth.privateDownloadUrl(url,expireInSeconds);
        return downloadUrl;
    }
    private void checkConfig(){
        if(StringUtils.isEmpty(config.getAccessKey())||StringUtils.isEmpty(config.getSecretKey())){
            throw new BusinessException("七牛云未配置");
        }

    }
}
